import {
	onLoad,
} from '@dcloudio/uni-app'
import {
	getEnv,
	aliAppId,
	weChatAppId,
} from '@/common/system.js'
import {
	objToParams
} from '@/common/common.js'
import {
	useCommonStore
} from '@/stores/common.js'
const commonStore = useCommonStore()

export function getProvider(service) {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: service,
			success: resolve,
			fail: reject
		});
	});
}

export function loginWeChat() {
	return new Promise((resolve, reject) => {
		wx.login({
			success: resolve,
			fail: reject
		});
	});
}

export function loginUni(provider) {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: provider,
			success: resolve,
			fail: reject
		});
	});
}

// 拉起平台支付
export function requestPayment(data) {
	let provider = ''
	// #ifdef MP-WEIXIN
	provider = 'wxpay'
	// #endif

	// #ifdef MP-ALIPAY
	provider = 'alipay'
	// #endif
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider: provider, // 支付渠道
			...data,
			success: resolve,
			fail: (e) => {
				reject(e)
				console.log('provider===》', provider);
				console.log('data===》', data);
				console.log('支付失败===》', e);
				uni.showModal({
					content: "支付失败，请重试。",
					showCancel: false
				})
			}
		})
	})
}

// 拉起平台扫一扫
export function scanCode() {
	return new Promise((resolve, reject) => {
		uni.scanCode({
			scanType: ['qrCode'], // 扫描二维码
			success: function(res) {
				console.log('扫码成功', res);
				resolve(res)
			},
			fail: function(err) {
				console.log('扫码失败', err);
				reject(err)
			}
		});
	})
}


// 获取平台code的方法
export function getPlatformCode() {
	return new Promise(async (resolve, reject) => {
		// 判断当前环境是否为微信小程序
		if (getEnv() == 'mp-weixin') {
			try {
				let res = await getProvider('oauth');
				if (res.provider.includes('weixin')) {
					// 微信小程序环境下
					if (process.env.NODE_ENV === 'development') {
						// console.log("当前环境为微信小程序开发环境");
					}
					let loginRes = await loginWeChat();
					let code = loginRes.code;
					resolve(code)
					// console.log("微信小程序登录code:", code);
					// 在这里可以将code发送到你的服务器
				}
			} catch (err) {
				reject(err)
				console.error("获取微信小程序code失败", err);
			}
		} else if (getEnv() == 'mp-alipay') {
			try {
				let res = await getProvider('oauth');
				if (res.provider.includes('alipay')) {
					// 支付宝小程序环境下
					if (process.env.NODE_ENV === 'development') {
						// console.log("当前环境为支付宝小程序开发环境");
					}
					let loginRes = await loginUni(res.provider);
					let code = loginRes.code;
					resolve(code)
					// console.log("支付宝小程序登录code:", code);
					// 在这里可以将code发送到你的服务器
				}
			} catch (err) {
				reject(err)
				console.error("获取支付宝小程序code失败", err);
			}
		} else if (/(micromessenger)/i.test(navigator.userAgent)) { // 判断当前环境是否为微信内置浏览器
			let query = encodeURIComponent(objToParams({
				...commonStore.deviceInfo
			}))
			// 微信公众账号环境下
			const appId = weChatAppId; // 替换为自己的公众号AppID
			const redirectUri = encodeURIComponent('https://pay.zzzfj.com/'); // 替换为自己的重定向地址
			const scope = 'snsapi_base'; // 或者 'snsapi_userinfo' 根据需求选择
			const state = query; // 可选
			const url =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;

			window.location.href = url; // 重定向到微信授权页面
		} else if (/(AlipayClient)/i.test(navigator.userAgent)) { // 判断当前环境是否为支付宝内置浏览器
			const appId = aliAppId; // 替换为自己的公众号AppID

			ap.getAuthCode({
				appId: `${appId}`,
				scopes: ['auth_base'],
			}, function(res) {
				resolve(res.authCode)
				// ap.alert(JSON.stringify(res));
			});
		} else {
			console.error('当前环境不支持微信登录');
		}
	})
}